'use client';

import React, { useEffect, useState } from 'react';
import { Card, Table, Tag, Typography, message, Button, Space, Empty, Select, Modal } from 'antd';
import { EyeOutlined, ReloadOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { 
  getRecruitmentAnnouncementsPaginated, 
  RecruitmentAnnouncement, 
  ApproveStatus, 
  PlanType,
  PaginatedResponse 
} from '@/lib/recruitment';
import { approveRecruitmentPlan } from '@/lib/approval';
import Layout from '@/components/Layout';
import AnnouncementDetailModal from '@/components/recruitment/AnnouncementDetailModal';
import dayjs from 'dayjs';

const { Title } = Typography;

const AnnouncementsPage = () => {
  const [announcements, setAnnouncements] = useState<RecruitmentAnnouncement[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedAnnouncement, setSelectedAnnouncement] = useState<RecruitmentAnnouncement | null>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedPlanType, setSelectedPlanType] = useState<number | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  const fetchAnnouncements = async (page = 1, pageSize = 10, planType: number | null = selectedPlanType) => {
    setLoading(true);
    setError(null);
    try {
      const params = {
        page,
        pageSize,
        ...(planType !== null && { planType })
      };
      
      console.log('发送请求参数:', params);
      const response = await getRecruitmentAnnouncementsPaginated(params);
      console.log('获取到的响应:', response);
      
      if (!response) {
        throw new Error('服务器返回空响应');
      }

      setAnnouncements(response.records || []);
      setPagination({
        current: response.current || page,
        pageSize: response.size || pageSize,
        total: response.total || 0
      });

      if (!response.records || response.records.length === 0) {
        message.info('暂无招聘公告数据');
      }

    } catch (error) {
      console.error('获取招聘公告失败:', error);
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      setError('获取招聘公告失败: ' + errorMessage);
      message.error('获取招聘公告失败，请稍后重试');
      
      setAnnouncements([]);
      setPagination({
        current: 1,
        pageSize: 10,
        total: 0
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAnnouncements();
  }, []);

  const handleTableChange = (pagination: any) => {
    fetchAnnouncements(pagination.current, pagination.pageSize, selectedPlanType);
  };

  const handleRefresh = () => {
    fetchAnnouncements(pagination.current, pagination.pageSize, selectedPlanType);
  };

  const handleViewAnnouncement = (record: RecruitmentAnnouncement) => {
    setSelectedAnnouncement(record);
    setModalVisible(true);
  };

  const handlePlanTypeChange = (value: number | null) => {
    console.log('选择的计划类型:', value);
    setSelectedPlanType(value);
    fetchAnnouncements(1, pagination.pageSize, value);
  };

  const handleApprove = async (record: RecruitmentAnnouncement, isApproved: boolean) => {
    const statusText = isApproved ? '通过' : '拒绝';
    
    Modal.confirm({
      title: `确认${statusText}审批`,
      content: `确定要${statusText}这条招聘计划吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await approveRecruitmentPlan({
            planId: record.planId,
            approveStatus: isApproved ? ApproveStatus.APPROVED : ApproveStatus.REJECTED
          });
          
          message.success(`审批${statusText}成功`);
          handleRefresh();
        } catch (error) {
          console.error('审批失败:', error);
          message.error('审批失败：' + (error instanceof Error ? error.message : '未知错误'));
        }
      }
    });
  };

  const planTypeOptions = [
    { label: '全部', value: null },
    { label: '管理岗位', value: PlanType.MANAGEMENT },
    { label: '专任教师', value: PlanType.TEACHER },
    { label: '其他岗位', value: PlanType.OTHER }
  ];

  const getPlanTypeTag = (type: number) => {
    switch (type) {
      case PlanType.MANAGEMENT:
        return <Tag color="blue">管理岗位</Tag>;
      case PlanType.TEACHER:
        return <Tag color="green">专任教师</Tag>;
      case PlanType.OTHER:
        return <Tag color="orange">其他岗位</Tag>;
      default:
        return <Tag>未知类型</Tag>;
    }
  };

  const getStatusTag = (status: number) => {
    switch (status) {
      case ApproveStatus.PENDING_PUBLISH:
        return <Tag color="warning">发布未审批</Tag>;
      case ApproveStatus.PENDING_MODIFY:
        return <Tag color="processing">修改未审批</Tag>;
      case ApproveStatus.APPROVED:
        return <Tag color="success">已通过</Tag>;
      case ApproveStatus.REJECTED:
        return <Tag color="error">已拒绝</Tag>;
      default:
        return <Tag>未知状态</Tag>;
    }
  };

  const columns = [
    {
      title: '计划编号',
      dataIndex: 'planCode',
      key: 'planCode',
    },
    {
      title: '计划名称',
      dataIndex: 'planName',
      key: 'planName',
    },
    {
      title: '类型',
      dataIndex: 'planType',
      key: 'planType',
      render: (type: number) => getPlanTypeTag(type),
    },
    {
      title: '发布日期',
      dataIndex: 'publishDate',
      key: 'publishDate',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD'),
    },
    {
      title: '开始日期',
      dataIndex: 'startDate',
      key: 'startDate',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD'),
    },
    {
      title: '结束日期',
      dataIndex: 'endDate',
      key: 'endDate',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD'),
    },
    {
      title: '状态',
      dataIndex: 'approveStatus',
      key: 'approveStatus',
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '创建人',
      dataIndex: 'createdBy',
      key: 'createdBy',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string | null) => date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
    {
      title: '更新人',
      dataIndex: 'updatedBy',
      key: 'updatedBy',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      render: (date: string | null) => date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: RecruitmentAnnouncement) => (
        <Space>
          <Button 
            type="primary" 
            icon={<EyeOutlined />} 
            onClick={() => handleViewAnnouncement(record)}
          >
            查看
          </Button>
          {(record.approveStatus === ApproveStatus.PENDING_PUBLISH || 
            record.approveStatus === ApproveStatus.PENDING_MODIFY) && (
            <>
              <Button
                type="primary"
                icon={<CheckCircleOutlined />}
                onClick={() => handleApprove(record, true)}
                style={{ backgroundColor: '#52c41a', borderColor: '#52c41a' }}
              >
                通过
              </Button>
              <Button
                danger
                type="primary"
                icon={<CloseCircleOutlined />}
                onClick={() => handleApprove(record, false)}
              >
                拒绝
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <Layout>
      <div style={{ padding: '24px' }}>
        <Card>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
            <Title level={2}>招聘公告列表</Title>
            <Space>
              <Select
                placeholder="选择计划类型"
                style={{ width: 200 }}
                options={planTypeOptions}
                value={selectedPlanType}
                onChange={handlePlanTypeChange}
                allowClear
                defaultValue={null}
              />
              <Button 
                type="primary" 
                icon={<ReloadOutlined />} 
                onClick={handleRefresh}
                loading={loading}
              >
                刷新
              </Button>
            </Space>
          </div>
          {error ? (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={
                <span style={{ color: '#ff4d4f' }}>
                  {error}
                  <br />
                  <Button type="link" onClick={handleRefresh}>点击重试</Button>
                </span>
              }
            />
          ) : (
            <Table
              loading={loading}
              columns={columns}
              dataSource={announcements}
              rowKey="planId"
              pagination={{
                ...pagination,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
              onChange={handleTableChange}
              locale={{
                emptyText: <Empty description="暂无招聘公告数据" />
              }}
            />
          )}
        </Card>
      </div>
      <AnnouncementDetailModal
        open={modalVisible}
        onClose={() => setModalVisible(false)}
        announcement={selectedAnnouncement}
      />
    </Layout>
  );
};

export default AnnouncementsPage; 